package com.mall.order.mq.delay;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.springframework.stereotype.Component;


import javax.annotation.PostConstruct;
import java.nio.charset.Charset;

@Slf4j
@Component
public class DelayOrderCancelProducer {

    private DefaultMQProducer producer;

    @PostConstruct
    public void init() {
        // 创建用于发送消息的Producer对象
        producer = new DefaultMQProducer("delay_order_cancel_producer");

        // 设置nameserver地址
        producer.setNamesrvAddr("127.0.0.1:9876");

        // 启动producer
        try {
            producer.start();
        } catch (MQClientException e) {
            e.printStackTrace();
        }

    }

    public boolean sendDelayOrderMessage(String orderId) {

        //  记录日志
        log.info("start sendDelayOrderMessage ....");
     // 准备好待发送的消息
        Message message = new Message();
        message.setTopic("delay_order_cancel");
        message.setBody(orderId.getBytes(Charset.forName("utf-8")));


        // 设置延迟消息的延迟级别
        // 非常简单 延迟级别
        // 1s 5s 10s 30s 1m 2m 3m 4m 5m 6m 7m 8m 9m 10m 20m 30m 1h  2h
        // 1  2  3  4   5  6  7  8  9  10 11 12 13 14  15   16  17  18
        message.setDelayTimeLevel(8);

        SendResult result = null;
        try {
            log.info("before send message ...." + orderId);
            result = producer.send(message);
        } catch (MQClientException | RemotingException | MQBrokerException | InterruptedException e) {
            e.printStackTrace();
            log.info("producer has some error ....");
        }

        if (result != null && SendStatus.SEND_OK.equals(result.getSendStatus())) {
            // 消息发送成功
            // 记录日志
            log.info("producer send message success ....");
            return true;
        }
        // 记录日志
        log.info("producer send message's result  error .....");
        return false;
    }

}
